package com.idenger.modules.edu.mobileWeb.user;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.idenger.common.mapper.JsonMapper;
import com.idenger.modules.edu.entity.common.BaseResponseMsg;
import com.idenger.modules.edu.entity.common.ResponseMsg;
import com.idenger.modules.edu.entity.wechat.EduWechatUser;
import com.idenger.modules.edu.mobileWeb.utils.RandomName;
import com.idenger.modules.sys.entity.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.foxinmy.weixin4j.cache.FileCacheStorager;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.jssdk.JSSDKAPI;
import com.foxinmy.weixin4j.jssdk.JSSDKConfigurator;
import com.foxinmy.weixin4j.model.WeixinAccount;
import com.foxinmy.weixin4j.mp.WeixinProxy;
import com.foxinmy.weixin4j.mp.api.OauthApi;
import com.foxinmy.weixin4j.mp.model.OauthToken;
import com.foxinmy.weixin4j.type.TicketType;
import com.idenger.common.utils.TokenProcessor;
import com.idenger.modules.edu.entity.user.EduUser;
import com.idenger.modules.edu.entity.user.UserToken;
import com.idenger.modules.edu.service.user.EduUserService;
import com.idenger.modules.edu.service.user.UserTokenService;
import com.idenger.modules.edu.service.wechat.EduWechatUserService;
import com.idenger.modules.edu.web.utils.Tools;
import com.idenger.modules.edu.web.utils.PayController;
import com.idenger.modules.sys.utils.UserUtils;

@Controller
@RequestMapping(value = "${mobilePath}/edu/user/eduWeiXin")
public class OAuthServletController extends PayController {
	
	@Autowired
	private EduWechatUserService wechatinfoService;
	@Autowired
	private EduUserService eduUserService;
	@Autowired
	private UserTokenService userTokenService;
	
	@RequestMapping(value = "signUp")
	public String signUp(EduUser eduUser, HttpServletRequest request, HttpServletResponse response, Model model) {
		logger.info("\n========mobile EleUserController signUp=======\n");
		return renderString(response, "");
	}
	protected synchronized String getUUIDStr(){
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	@RequestMapping(value = "oAuth")
	public String OAuthServlet(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
			System.out.println("微信授权接口测试");
			BaseResponseMsg baseResponseMsg = null;
			String code = request.getParameter("code");
			WeixinAccount account = new WeixinAccount(wxAppId, wxKey);
//			WeixinAccount account = new WeixinAccount("wx7a1e30674570d25c","233481cd36da3bc19d370b7e388963af");

			OauthApi oauthApi = new OauthApi(account);
			try {
			OauthToken token = oauthApi.getAuthorizationToken(code);
			com.foxinmy.weixin4j.mp.model.User user = oauthApi.getAuthorizationUser(token);
	        String UserJson = JsonMapper.toJsonString(user);
	        String bindType = "weixin";
	       // FreshUser eleUser = freshUserService.getByOpenId(user.getOpenId());
	        //if(eleUser == null){
			//没有正式接入正式的注册，一些字段先没写的顶着
			
	        //先查询是不是存了微信消息，如果存了，修改。根据openID查询
	        EduWechatUser wechat = new EduWechatUser();
	        wechat.setOpenid(user.getOpenId());
	        List<EduWechatUser> wechatinfos = wechatinfoService.getWechatinfo(wechat);
        	User user2 = UserUtils.getUser();
			EduUser eduUser = new EduUser();
	        if(wechatinfos.size()>0){
	        	//则说明之前存过该用户的信息，做修改
	        	EduWechatUser woInfo = wechatinfos.get(0);
	        	woInfo.setNickname(Tools.filterEmoji(user.getNickName()));
	        	woInfo.setSex(user.getGender()+"");//性别
	        	woInfo.setProvince(user.getProvince());
	        	woInfo.setCity(user.getCity());
	        	woInfo.setCountry(user.getCountry());
	        	woInfo.setHeadimgurl(user.getHeadimgurl());
	        	woInfo.setIssubscribe(user.isSubscribe()+"");
	        	woInfo.setSubscribeTime(new Date(user.getSubscribeTime() * 1000l));
	        	woInfo.setUnionid(user.getUnionId());
	        	woInfo.setLanguage(user.getLanguage());
	        	woInfo.setRemark(user.getRemark());
	        	woInfo.setGroupid(user.getGroupId()+"");
	        	woInfo.setCreateBy(user2);
	        	woInfo.setUpdateBy(user2);
	        	woInfo.setUpdateDate(new Date());
	        	wechatinfoService.save(woInfo);
	        }else{
	        	//新增一条用户微信的信息
	        	EduWechatUser wechatinfo = new EduWechatUser();
				wechatinfo.setOpenid(user.getOpenId());
				wechatinfo.setNickname(Tools.filterEmoji(user.getNickName()));
				wechatinfo.setSex(user.getGender()+"");//性别
				wechatinfo.setProvince(user.getProvince());
				wechatinfo.setCity(user.getCity());
				wechatinfo.setCountry(user.getCountry());
				wechatinfo.setHeadimgurl(user.getHeadimgurl());
				wechatinfo.setIssubscribe(user.isSubscribe()+"");
				wechatinfo.setSubscribeTime(new Date(user.getSubscribeTime() * 1000l));
				wechatinfo.setUnionid(user.getUnionId());
				wechatinfo.setLanguage(user.getLanguage());
				wechatinfo.setRemark(user.getRemark());
				wechatinfo.setGroupid(user.getGroupId()+"");
				wechatinfo.setUpdateBy(user2);
				wechatinfo.setCreateBy(user2);
				wechatinfo.setCreateDate(new Date());
				wechatinfo.setUpdateDate(new Date());
				wechatinfoService.save(wechatinfo);
				//新增一个用户
				eduUser.setLoginName(Tools.filterEmoji(user.getNickName()));
				eduUser.setImage("/static/default.png");
				eduUser.setUserType("1");//标记为微信端注册用户
				eduUser.setPassword(DigestUtils.md5Hex("12345678"));
				eduUser.setOpenid(user.getOpenId());
				eduUser.setCreateBy(user2);
				eduUser.setUpdateBy(user2);
				eduUser.setCreateDate(new Date());
				eduUser.setCreateDate(new Date());
				eduUserService.save(eduUser);
	        }
	        EduUser eduUser2 = eduUserService.findByOpenId(user.getOpenId());
    		String tokenId = addToken(eduUser2.getId(), eduUser2);
			logger.info("微信授权CODE ：参数code=" + "http://www.hi-in.com:8100/#/registerHome/"+token.getOpenId());
			//	return "redirect:" + "http://www.hi-in.com:8100/#/registerHome/"+token.getOpenId();
			return "redirect:" + "http://xin.baojiaoshou.com?openId="+token.getOpenId()+"&tokenId="+tokenId;
			
		//	}
			//生成新的token
			// TODO Auto-generated catch block
//			String tokenId = TokenProcessor.getInstance().generateToken(currentUser.getId(), true);// 生成新的token
			//systemService.addUserToken(new Token(currentUser.getId(), "", tokenId, 1));// 生成新的token记录
			 //如何已经注册返回登录
			// TODO Auto-generated catch block
			} catch (WeixinException e) {
				e.printStackTrace();
			}
	        return null;
	}
	
	@RequestMapping(value = "getjsConfig", method = RequestMethod.GET)
	public String getjsConfig(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws  WeixinException {
		BaseResponseMsg baseResponseMsg;
		String url = request.getParameter("url");//Tools.getRequestValue(request, jsonData, "url");
		// 默认使用classpath目录下的weixin4j.properties配置的账号信息,也可以用spring注入
				WeixinProxy weixinProxy = new WeixinProxy(new WeixinAccount("wx7a1e30674570d25c", "233481cd36da3bc19d370b7e388963af"),
						new FileCacheStorager<com.foxinmy.weixin4j.model.Token>());
				// 调用js接口
				JSSDKConfigurator jssdk = new JSSDKConfigurator(weixinProxy.getTicketManager(TicketType.jsapi));
				jssdk.apis(JSSDKAPI.SHARE_APIS);
				//jssdk.appId("wxd1aff78b099d8803");
				jssdk.appId("wx7a1e30674570d25c");
				baseResponseMsg =new BaseResponseMsg(new ResponseMsg("0", "success"));
				baseResponseMsg.addData("status", "请求成功");
				baseResponseMsg.addData("result",jssdk.toJSONConfig(url));
				return renderString(response,baseResponseMsg);
	}
	/***
	 * 生成用户名，如果该用户名已存在，则递归
	 * @return
	 */
	public String generatingAccount(){
		EduUser eduUser = new EduUser();
		String name = RandomName.getRandomEnglishName();
		eduUser.setLoginName(name);
		EduUser eduUser2 = eduUserService.findByAccount(eduUser);
		if(eduUser2 != null){
			generatingAccount();
		}
		return name;
	}
	
	private String addToken(String id, EduUser auth) {
		UserToken token = userTokenService.queryUserTokenByUserId(String.valueOf(auth.getId()));
		if (token != null) {
            token.setValid(0);
            userTokenService.updateUserToken(token);
        }
		String tokenId = TokenProcessor.getInstance().generateToken(String.valueOf(auth.getId()), true);// 生成新的token
		UserToken newToken = new UserToken();
		newToken.setUserId(String.valueOf(auth.getId()));
		newToken.setToken(tokenId);
		newToken.setPhone(id);
		newToken.setModifyTime(new Date());
		newToken.setUuid(getUUIDStr());
		newToken.setValid(1);
		userTokenService.addUserToken(newToken);  // 生成新的token记录
		return tokenId;
	}
}


